<template>
  <div class="exam-records-list-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>考试提交记录 (考试 ID: {{ examId }})</span>
          <el-button style="margin-left: auto;" @click="goBack">返回</el-button>
        </div>
      </template>

      <el-table :data="records" v-loading="isLoading" style="width: 100%">
        <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
        <el-table-column prop="studentId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="submitTime" label="提交时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" width="100">
           <template #default="{ row }">
            {{ row.score === null ? '-' : row.score }}
          </template>
        </el-table-column>
         <el-table-column prop="passed" label="是否通过" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.passed !== null" :type="row.passed ? 'success' : 'danger'">
              {{ row.passed ? '是' : '否' }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="答卷状态" width="120">
           <template #default="{ row }">
            <el-tag :type="getRecordStatusTagType(row.status)">
              {{ getRecordStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
         <el-table-column prop="markingStatus" label="批改状态" width="120">
           <template #default="{ row }">
            <el-tag :type="getMarkingStatusTagType(row.markingStatus)">
              {{ getMarkingStatusText(row.markingStatus) }}
            </el-tag>
          </template>
        </el-table-column>
         <el-table-column prop="suspiciousLevel" label="可疑等级" width="100">
             <template #default="{ row }">
                 <el-rate v-model="row.suspiciousLevel" disabled show-score text-color="#ff9900" score-template="{value}" :max="5"></el-rate>
             </template>
         </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="canStartMarking(row)" 
              type="primary" 
              link 
              size="small" 
              @click="goToMarking(row.id)"
            >
              开始批改
            </el-button>
             <el-button 
              v-else-if="canContinueMarking(row)" 
              type="warning" 
              link 
              size="small" 
              @click="goToMarking(row.id)"
            >
              继续批改
            </el-button>
             <el-button 
              v-else-if="row.markingStatus === 'COMPLETED'" 
              type="info" 
              link 
              size="small" 
              @click="viewMarkingResult(row.examId, row.studentId)"
            >
              查看结果
            </el-button>
             <el-button v-else disabled type="info" link size="small">
               无需操作
             </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 可以添加分页控件，如果后端支持 -->
       <el-pagination
        v-if="totalRecords > pageSize"
        layout="prev, pager, next, total"
        :total="totalRecords"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getExamRecords } from '@/services/examService';
import { ElMessage, ElTag, ElRate } from 'element-plus';

const route = useRoute();
const router = useRouter();

const examId = ref(route.params.id); // 从路由参数获取考试ID
const records = ref([]);
const isLoading = ref(false);
const totalRecords = ref(0);
const currentPage = ref(1);
const pageSize = ref(10); // 假设每页10条

const fetchRecords = async () => {
  if (!examId.value) {
    ElMessage.error('无效的考试ID');
    return;
  }
  isLoading.value = true;
  try {
    // 注意：当前 getExamRecords 不支持分页，如果需要，后端和 service 都需要修改
    const response = await getExamRecords(examId.value);
    if (response && response.success) {
      records.value = response.data || [];
      totalRecords.value = records.value.length; // 前端模拟总数
    } else {
      // 错误已在 service 层处理
      records.value = [];
      totalRecords.value = 0;
    }
  } catch (error) {
    console.error("Error fetching exam records:", error);
    ElMessage.error("加载考试记录失败");
    records.value = [];
    totalRecords.value = 0;
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchRecords();
});

// --- Helper Functions ---

// 格式化日期时间 (可以考虑提取到 utils)
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  try {
    return new Date(dateTimeString).toLocaleString();
  } catch (e) {
    return dateTimeString;
  }
};

// 获取答卷状态文字
const getRecordStatusText = (status) => {
  const map = {
    NOT_STARTED: '未开始',
    IN_PROGRESS: '进行中',
    SUBMITTED: '已提交',
    MARKED: '已批改'
  };
  return map[status] || status;
};

// 获取答卷状态标签类型
const getRecordStatusTagType = (status) => {
  const map = {
    NOT_STARTED: 'info',
    IN_PROGRESS: 'warning',
    SUBMITTED: 'primary',
    MARKED: 'success'
  };
  return map[status] || '';
};

// 获取批改状态文字
const getMarkingStatusText = (status) => {
  const map = {
    PENDING: '待批改',
    IN_PROGRESS: '批改中',
    COMPLETED: '已完成'
  };
  return map[status] || '未知';
};

// 获取批改状态标签类型
const getMarkingStatusTagType = (status) => {
  const map = {
    PENDING: 'warning',
    IN_PROGRESS: 'primary',
    COMPLETED: 'success'
  };
  return map[status] || 'info';
};

// 判断是否可以开始批改
const canStartMarking = (record) => {
    // 只有已提交且待批改的记录才能开始
    return record.status === 'SUBMITTED' && record.markingStatus === 'PENDING';
};

// 判断是否可以继续批改
const canContinueMarking = (record) => {
    // 只有已提交且批改中的记录才能继续
    return record.status === 'SUBMITTED' && record.markingStatus === 'IN_PROGRESS';
};


// --- Event Handlers ---

const goBack = () => {
  // 可以根据来源决定返回到哪里，例如 ExamList 或 ExamDetail
  // router.back(); 
  // 或者固定返回到考试列表
  router.push({ name: 'ExamList' }); 
};

const handlePageChange = (page) => {
  currentPage.value = page;
  // 如果后端支持分页，调用 fetchRecords()
  ElMessage.info(`切换到第 ${page} 页 (前端分页模拟)`);
};

// 跳转到批改界面
const goToMarking = (recordId) => {
  if (!recordId) return;
  router.push({ name: 'ExamMarking', params: { recordId: recordId } });
};

// 查看批改结果 (修改：接收 examId 和 studentId, 并通过 query 传递 studentId)
const viewMarkingResult = (examId, studentId) => {
  if (!examId || !studentId) {
      ElMessage.warning('无法获取考试ID或学生ID，无法查看结果');
      return;
  }
  // 使用 query 参数传递 studentId
  router.push({ 
      name: 'MyExamRecordDetail', 
      params: { examId: examId }, 
      query: { studentId: studentId } 
  });
};

</script>

<style scoped>
.exam-records-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 